package com.heima.tradeservice.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.api.client.CartClient;
import com.heima.api.client.ItemClient;
import com.heima.api.domain.dto.ItemDTO;
import com.heima.api.domain.dto.OrderDetailDTO;
import com.heima.tradeservice.constants.MqConstants;
import com.heima.tradeservice.domain.dto.OrderFormDTO;
import com.heima.tradeservice.domain.po.Order;
import com.heima.tradeservice.domain.po.OrderDetail;
import com.heima.tradeservice.mapper.OrderMapper;
import com.heima.tradeservice.service.IOrderDetailService;
import com.heima.tradeservice.service.IOrderService;
import com.hmall.common.exception.BadRequestException;
import com.hmall.common.utils.UserContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2023-05-05
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private final ItemClient itemClient;
    private final CartClient cartClient;
//    private final IItemService itemService;
    private final IOrderDetailService detailService;
//    private final ICartService cartService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
//    @Transactional   //TODO 下单 分布式事务
    @GlobalTransactional
    public Long createOrder(OrderFormDTO orderFormDTO) {
        // 1.订单数据
        Order order = new Order();
        // 1.1.查询商品
        List<OrderDetailDTO> detailDTOS = orderFormDTO.getDetails();
        // 1.2.获取商品id和数量的Map
        Map<Long, Integer> itemNumMap = detailDTOS.stream()
                .collect(Collectors.toMap(OrderDetailDTO::getItemId, OrderDetailDTO::getNum));
        Set<Long> itemIds = itemNumMap.keySet();
        // 1.3.查询商品
//        List<ItemDTO> items = itemService.queryItemByIds(itemIds);
        List<ItemDTO> items = itemClient.queryItemByIds(itemIds.stream().collect(Collectors.toList()));
        if (items == null || items.size() < itemIds.size()) {
            throw new BadRequestException("商品不存在");
        }
        // 1.4.基于商品价格、购买数量计算商品总价：totalFee
        int total = 0;
        for (ItemDTO item : items) {
            total += item.getPrice() * itemNumMap.get(item.getId());
        }
        order.setTotalFee(total);
        // 1.5.其它属性
        order.setPaymentType(orderFormDTO.getPaymentType());
//        TODO 获取用户ID
        order.setUserId(UserContext.getUser());
        order.setStatus(1);
        // 1.6.将Order写入数据库order表中
        save(order);

        // 2.保存订单详情
        List<OrderDetail> details = buildDetails(order.getId(), items, itemNumMap);
        detailService.saveBatch(details);

        // 3.清理购物车商品
//        cartService.removeByItemIds(itemIds);

//          cartClient.deleteCartItemByIds(itemIds.stream().collect(Collectors.toList()));
//        AMQP
        List<Long> collect = itemIds.stream().collect(Collectors.toList());
        try {
            rabbitTemplate.convertAndSend("trade.topic", "order.create", collect, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    Long userId = UserContext.getUser();
                    message.getMessageProperties().setHeader("userId", userId);
                    return message;
                }
            });
        } catch (AmqpException e) {
            log.error("发送清空购物车消息失败，商品ids：{}", itemIds.stream().collect(Collectors.toList()), e);
        }

        // 4.扣减库存
        try {
            itemClient.deductStock(detailDTOS);
        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }
        // 5.发送延迟消息
        rabbitTemplate.convertAndSend(MqConstants.DELAY_EXCHANGE_NAME, MqConstants.DELAY_ORDER_ROUTING_KEY, order.getId(), message -> {
            message.getMessageProperties().setDelay(10000);
            return message;
        });
        return order.getId();
    }

//    MQ 消费者可靠性 业务幂等性 业务判断
    @Override
    public void markOrderPaySuccess(Long orderId) {
//        判断订单支付状态是否是未支付，如果不是则不用重复该业务
//        Order o = getById(orderId);
//        if (o == null || o.getStatus() != 1){
//            return;
//        }
//        Order order = new Order();
//        order.setId(orderId);
//        order.setStatus(2);
//        order.setPayTime(LocalDateTime.now());
//        updateById(order);
//       消除线程安全风险
        lambdaUpdate()
                .set(Order::getPayTime, LocalDateTime.now())
                .set(Order::getStatus, 2)
                .eq(Order::getId, orderId)
                .eq(Order::getStatus, 1)
                .update()
        ;
    }

    @Override
    public void cancelOrder(Long orderId) {

        lambdaUpdate()
                .set(Order::getStatus,5)
                .eq(Order::getId,orderId)
                .set(Order::getCloseTime,LocalDateTime.now())
                .update();


    }

    private List<OrderDetail> buildDetails(Long orderId, List<ItemDTO> items, Map<Long, Integer> numMap) {
        List<OrderDetail> details = new ArrayList<>(items.size());
        for (ItemDTO item : items) {
            OrderDetail detail = new OrderDetail();
            detail.setName(item.getName());
            detail.setSpec(item.getSpec());
            detail.setPrice(item.getPrice());
            detail.setNum(numMap.get(item.getId()));
            detail.setItemId(item.getId());
            detail.setImage(item.getImage());
            detail.setOrderId(orderId);
            details.add(detail);
        }
        return details;
    }
}
